package com.ruoyi.controller;

import java.util.List;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.util.ObjectUtil;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.entity.Project;
import com.ruoyi.common.entity.ProjectItem;
import com.ruoyi.common.service.IProjectItemsService;
import com.ruoyi.common.service.ProjectService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 课程目录Controller
 * 
 * @author ruoyi
 * @date 2025-08-17
 */
@RestController
@RequestMapping("/projectitems/items")
public class ProjectItemsController extends BaseController
{
    @Autowired
    private IProjectItemsService projectItemsService;
    @Autowired
    private ProjectService  projectService;



    @GetMapping("/detail/{id}")
    public R<Project> getProject(@PathVariable Long id) {
        Project project = projectService.getProjectById(id);

        if (project != null) {
            return  R.ok(project);
        } else {
            return R.fail(HttpStatus.NOT_FOUND, "项目不存在");
        }
    }

    /**
     * 新增项目
     * POST /api/projects - 创建资源
     */
    @PostMapping("/detail")
    public R<?> createProject(@Validated @RequestBody Project project) {
        try {
            boolean success = projectService.addProject(project);
            if (success) {
                return  R.ok(project, "项目创建成功");
            } else {
                return R.fail("项目创建失败");
            }
        } catch (Exception e) {
            return R.fail("项目创建失败: " + e.getMessage());
        }
    }


    @PostMapping("/detailUpdate")
    public R<?> updateProject(@Validated @RequestBody Project project) {
        // 确保路径ID与请求体ID一致
        Project projectById = projectService.getProjectById(project.getId());
        if (ObjectUtil.isNull(projectById)){
            throw new RuntimeException("项目不存在");
        }

        try {
            boolean success = projectService.updateProject(project);
            if (success) {
                return  R.ok(null, "项目更新成功");
            } else {
                return R.fail(HttpStatus.NOT_FOUND, "项目不存在或更新失败");
            }
        } catch (Exception e) {
            return R.fail("项目更新失败: " + e.getMessage());
        }
    }

    /**
     * 部分更新项目
     * PATCH /api/projects/{id} - 部分更新资源
     */
    @PatchMapping("/detail/{id}")
    public R<?> partialUpdateProject(
            @PathVariable Long id,
            @RequestBody Project project) {
        // 仅更新提供的字段，确保ID一致
        project.setId(id);

        try {
            boolean success = projectService.updateProject(project);
            if (success) {
                return R.ok(null, "项目更新成功");
            } else {
                return R.fail(HttpStatus.NOT_FOUND, "项目不存在或更新失败");
            }
        } catch (Exception e) {
            return R.fail("项目更新失败: " + e.getMessage());
        }
    }

    /**
     * 删除项目
     * DELETE /api/projects/{id} - 删除资源
     */
    @DeleteMapping("/detail/{id}")
    public void deleteProject(@PathVariable Long id) {
        boolean success = projectService.deleteProject(id);
        if (!success) {
            throw new RuntimeException("项目删除失败");
        }
    }








    /**
     * 查询课程目录列表
     */
    @PreAuthorize("@ss.hasPermi('projectitems:items:list')")
    @GetMapping("/list")
    public TableDataInfo list(ProjectItem projectItems)
    {
        startPage();
        List<ProjectItem> list = projectItemsService.selectProjectItemsList(projectItems);
        return getDataTable(list);
    }

    /**
     * 导出课程目录列表
     */
    @PreAuthorize("@ss.hasPermi('projectitems:items:export')")
    @Log(title = "课程目录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ProjectItem projectItems)
    {
        List<ProjectItem> list = projectItemsService.selectProjectItemsList(projectItems);
        ExcelUtil<ProjectItem> util = new ExcelUtil<ProjectItem>(ProjectItem.class);
        util.exportExcel(response, list, "课程目录数据");
    }

    /**
     * 获取课程目录详细信息
     */
    @PreAuthorize("@ss.hasPermi('projectitems:items:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(projectItemsService.selectProjectItemsById(id));
    }

    /**
     * 新增课程目录
     */
    @PreAuthorize("@ss.hasPermi('projectitems:items:add')")
    @Log(title = "课程目录", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ProjectItem projectItems)
    {
        return toAjax(projectItemsService.insertProjectItems(projectItems));
    }

    /**
     * 修改课程目录
     */
    @PreAuthorize("@ss.hasPermi('projectitems:items:edit')")
    @Log(title = "课程目录", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ProjectItem projectItems)
    {
        String s = projectItemsService.updateProjectItems(projectItems);
        return AjaxResult.success().put("msg",s);
    }

    /**
     * 删除课程目录
     */
    @PreAuthorize("@ss.hasPermi('projectitems:items:remove')")
    @Log(title = "课程目录", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {

        return toAjax(projectItemsService.deleteProjectItemsByIds(ids));
    }
}
